<template>
  <input
    v-if="type==='input'"
    ref="input"
    class="v-simple-input"
    :value="value"
    :readonly="readonly"
    type="text"

    @input="handleInput"
    @blur="$emit('blur',$event)"
    @keyup.enter="$emit('enter',$event)"
    @focus="handleFocus"
  />
  <textarea
    v-else-if="type==='textarea'"
    ref="input"
    class="v-simple-input"
    :style="textareaStyle"
    :value="value"
    :readonly="readonly"
    type="text"
    @input="handleInput"
    @blur="$emit('blur',$event)"
    @keyup.enter="$emit('enter',$event)"
    @focus="handleFocus"
  />

</template>
<script>
import calcTextareaHeight from './calcTextareaHeight';
export default {
  name: 'comp-simple-input',
  components: {
  },
  props: {
    value: [String, Number, Boolean],
    readonly: Boolean,
    type: String,
    autosize: {
      type: Object,
      default: () => ({ minRows: 2, maxRows: 5 })
    }
  },
  data() {
    return {
      curValue: this.value,
      textareaCalcStyle: {},

    };
  },
  computed: {
    textareaOption(){
      return { ...defaultTextareaOpt, ...this.textareaOpt };
    },
    curHeightPx(){
      return this.curHeight + 'px';

    },
    textareaStyle() {
      return this.textareaCalcStyle;
    },
    //// inputType(){
    ////   if (this.type == 'textarea'){
    ////     return 'textarea';
    ////   } else {
    ////     return 'text';
    ////   }
    //// }

  },
  watch: {
    value(val){
      this.curValue = val;

    }

  },
  mounted(){
    this.resizeTextarea();
  },
  methods: {
    handleInput(event){
      this.curValue = event.target.value;
      this.$emit('input', this.curValue);
      this.resizeTextarea();
    },
    select(){
      this.$refs.input.select();
    }, 
    handleFocus(event){
      this.$emit('focus', { event, input: this.$refs.input });
    },
    resizeTextarea() {
      const { autosize, type } = this;
      if (type !== 'textarea' || !this.$refs.input) return;
      const minRows = autosize.minRows;
      const maxRows = autosize.maxRows;

      this.textareaCalcStyle = calcTextareaHeight(this.$refs.input, minRows, maxRows);
    },
    //// resizeTextarea(){
    ////   if (this.type !== 'textarea') return;
    ////   console.log('resize');
    ////   const input = this.$refs.input;
    ////   if (input.scrollHeight >  this.textareaOption.maxHeight){
    ////     this.curHeight = this.textareaOption.maxHeight;

    ////   } else if (input.scrollHeight < this.textareaOption.minHeight) {
    ////     this.curHeight = this.textareaOption.minHeight;

    ////   } else {
    ////     this.curHeight = input.scrollHeight;
    ////   }
    
    //// }

  }
};
</script>
<style lang="scss">
.v-simple-input {
  border: none;
  outline: none;
  width: 100%;
  resize:none;
}
</style>